import os
import gc
from io import StringIO
from flask import Blueprint, jsonify, request, render_template, current_app
from pyverilog.vparser.parser import parse
from pyverilog.dataflow.dataflow_analyzer import VerilogDataflowAnalyzer
from .utils import draw_ast, show

bp = Blueprint('routes', __name__)

# 允许的文件扩展名
ALLOWED_EXTENSIONS = {'v'}


# 检查文件名是否合法
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


# 测试，helloWorld
@bp.route('/api/hello', methods=['GET'])
def hello():
    return jsonify({"message": "Hello from Flask!"})


# 上传文件,编译verilog文件
@bp.route('/api/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return jsonify({"error": "No file part"}), 400

    file = request.files['file']

    # 如果没有选择文件
    if file.filename == '':
        return jsonify({"error": "No selected file"}), 400

    # 检查文件扩展名是否合法
    if file and allowed_file(file.filename):
        filename = file.filename
        file_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)

        # 确保上传目录存在
        if not os.path.exists(current_app.config['UPLOAD_FOLDER']):
            os.makedirs(current_app.config['UPLOAD_FOLDER'])

        # 保存文件
        file.save(file_path)
        # 删除旧的中间文件
        if os.path.exists(os.path.join(current_app.config['OUTPUT_FOLDER'], 'parser.out')):
            os.remove(os.path.join(current_app.config['OUTPUT_FOLDER'], 'parser.out'))
        if os.path.exists(os.path.join(current_app.config['OUTPUT_FOLDER'], 'parsetab.py')):
            os.remove(os.path.join(current_app.config['OUTPUT_FOLDER'], 'parsetab.py'))
        # 解析 Verilog 文件
        ast, _ = parse([file_path], outputdir=current_app.config['OUTPUT_FOLDER'])
        print(file_path)
        output_buffer = StringIO()
        ast_str = show(ast, buf=output_buffer)  # 捕获输出
        # 绘制图像
        dot = draw_ast(ast)
        ast_graph_path = os.path.join(current_app.config['STATIC_FOLDER'], filename)
        dot.render(filename=ast_graph_path, format='png', cleanup=True)  # 生成 ast_graph.png
        # 获取 AST 字符
        gc.collect()
        return jsonify({"ast": f"{ast_str}"}), 200
    else:
        return jsonify({"error": "Invalid file type. Only .v files are allowed."}), 400


@bp.route('/api/dataFlow', methods=['GET'])
def dataflow():
    filename = request.args.get('fileName')
    print(filename)
    if os.path.exists(os.path.join(current_app.config['UPLOAD_FOLDER'], filename)):
        # analyzer = VerilogDataflowAnalyzer([filename])
        # analyzer.generate()
        return jsonify({"dataFlow": "success"}), 200
    else:
        return jsonify({"error": "Failed."}), 400
